package actions;

import exceptions.UsernameExistsException;
import gui.LoginDialog;
import gui.MainFrame;

import java.awt.event.ActionEvent;
import java.net.MalformedURLException;
import java.net.URL;

import javax.swing.AbstractAction;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;

import model.LoggedInUsers;
import model.User;
import webservice.ChatServiceWS;

@SuppressWarnings("serial")
public class LoginAction extends AbstractAction {

	public LoginAction() {
		// TODO Auto-generated constructor stub
		super();
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		Service mojServis;
		LoginDialog ld = new LoginDialog();
		ld.setVisible(true);
		try {
			mojServis = Service
					.create(new URL(
							"http://"+MainFrame.getInstance().getLocalAddress()+":8080/chatAgentsEJB/ChatService/ChatServiceBean?wsdl"),
							new QName("http://1337.webservice", "ChatService"));
			ChatServiceWS servis = mojServis.getPort(ChatServiceWS.class);

			boolean response=false;
			User user;// = MainFrame.getInstance().getCurrentUser();
			//if(user==null)
			//	return;
			//user = servis.register("cale2", "srndac");
			//user = new User(MainFrame.getInstance().getUsername(), MainFrame.getInstance().getPassword());
			//user=temp;
			if(MainFrame.getInstance().isRegisterUser()) {
				user = servis.register(MainFrame.getInstance().getLoginUsername(), MainFrame.getInstance().getLoginPassword());
				if(user!=null){
					response=true;

					MainFrame.getInstance().setCurrentUser(user);
				}
				MainFrame.getInstance().setLoginUsername(null);
				MainFrame.getInstance().setLoginPassword(null);
			}
			else{
				user = servis.login(MainFrame.getInstance().getLoginUsername(), MainFrame.getInstance().getLoginPassword());
				if(user!=null){
					response=true;

					MainFrame.getInstance().setCurrentUser(user);
				}
				MainFrame.getInstance().setLoginUsername(null);
				MainFrame.getInstance().setLoginPassword(null);
			}
			if(response) {
				System.out.println("uspeo login");
				MainFrame.getInstance().getInputPanel().enableSending();
				MainFrame.getInstance().setCurrentUser(user);
				LoggedInUsers users=servis.getAllUsers();
				MainFrame.getInstance().initModel(users.getLoggedUsers());
				MainFrame.getInstance().setTitle("Logged in as: "+user.toString());
				MainFrame.getInstance().getInputPanel().enableLogin(false);
				//MainFrame.getInstance().connectToServer();
			}
			else
			{
				System.out.println("Neuspesno logovanje. Kombinacija lozinka/sifra nije dobra ili vec postoji korisnik koji je ulogovan pod tim imenom.");
			}
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
		}
		catch (UsernameExistsException e13) {
			// TODO Auto-generated catch block
			System.out.println("Vec postoji korisnik koji je registrovan sa tim imenom");
		}
	}
}
